/*
* @Author: Someu
* @Date:   2017-11-28 11:39:19
* @Last Modified by:   Someu
* @Last Modified time: 2017-12-03 16:54:10
*/

require('./index.css');
require('page/common/nav-simple/index.css');

var _mm     = require('util/mm.js');
var _user   = require('service/user-service.js');

var formError = {
    show : function(errMsg){
        $('.error-item').show().find('.err-msg').text(errMsg);
    },
    hide : function(){
        $('.error-item').hide().find('.err-msg').text('');
    }
};

var page = {
    init : function(){
        $('#username').focus();
        this.bindEvent();
    },
    bindEvent : function(){
        var _this = this;
        //如果按下回车，也提交
        $('.user-content').keyup(function(e){
            //keyCode == 13表示回车键
            if(e.keyCode === 13){
                _this.submit();
            }
        });
        //点击登录按钮
        $('#submit').click(function(){
            _this.submit();
        });     
    },
    submit : function(){
        var formData = {
                username : $.trim($('#username').val()),
                password : $.trim($('#password').val()),
            },
            //表单验证结果
            validateResult = this.formValidate(formData);
        //验证成功
        if(validateResult.status){
            //提交
            _user.login(formData, function(res){
                window.location.href = _mm.getUrlParam('redirect');
            }, function(errMsg){
                formError.show(errMsg);
            });
        }
        //验证失败
        else{
            //错误提示
            formError.show(validateResult.msg);
        }
    },
    formValidate : function(formData){
        var result = {
            status : false,
            msg    : ''
        };
        if(!_mm.validata(formData.username, 'require')){
            result.msg = '用户名不能为空';
            return result;
        }
        if(!_mm.validata(formData.password, 'require')){
            result.msg = '密码不能为空';
            return result;
        }
        result.status  = true;
        result.msg = '验证通过';
        return result;
    }
};

$(function(){
    page.init();
});
